package net.livingflow.web.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import net.livingflow.Constants;
import net.livingflow.model.Flow;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-11-28
 */
@Path("/flows")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class FlowsResource extends BaseResource {

	public List<Flow> getFlows() {
		return flowService.latest();
	}

	@GET
	@Path("create")
	public Response createFlow(@DefaultValue("0") @PathParam("packId") long packId) {
		return Response.ok(new Viewable("create", packId)).build();
	}

	@POST
	@Path("ajax/create")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String postPackageForm(@FormParam("packId") long packId, @FormParam("flow") String json) {
		Gson gson = new Gson();
		Flow flow = gson.fromJson(json, Flow.class);
		flow.setPackId(packId);
		flow.setOwner(getUserName());
		flowService.add(flow);

		return Constants.STATUS_OK;
	}
}
